import type React from "react";
import { StrictMode, useEffect } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter, RouterProvider } from "@tanstack/react-router";
import NotFound from "./routes/-404";
// Import the generated route tree
import { routeTree } from "./routeTree.gen";
import useAuthStore from "./store/auth";

// Create a new router instance
const router = createRouter({
  routeTree,
  defaultStaleTime: Number.POSITIVE_INFINITY,
  defaultNotFoundComponent() {
    return <NotFound />;
  },
  defaultViewTransition: {
    types: ["fade"],
  },
});

const queryClient = new QueryClient();

// Register the router instance for type safety
declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}

function App({ children }: { children: React.ReactNode }) {
  const auth = useAuthStore();

  useEffect(() => {
    auth.load();
  }, []);

  return <>{children}</>;
}

// Render the app
const rootElement = document.getElementById("root");
if (rootElement && !rootElement.innerHTML) {
  createRoot(rootElement).render(
    <StrictMode>
      <QueryClientProvider client={queryClient}>
        <App>
          <RouterProvider router={router} />
        </App>
      </QueryClientProvider>
    </StrictMode>,
  );
}
